package config

import (
	"bytes"
	"gin.project.template/global"
	"github.com/gin-gonic/gin"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/buffer"
	"go.uber.org/zap/zapcore"
	"net"
	"net/http"
	"net/http/httputil"
	"os"
	"runtime/debug"
	"strings"
	"time"
)

type Zap struct {
	Level      string `mapstructure:"level" json:"level" yaml:"level"`
	Filename   string `mapstructure:"filename" json:"filename" yaml:"filename"`
	MaxSize    int    `mapstructure:"max_size" json:"max_size" yaml:"max_size"`
	MaxAge     int    `mapstructure:"max_age" json:"max_age" yaml:"max_age"`
	MaxBackups int    `mapstructure:"max_backups" json:"max_backups" yaml:"max_backups"`
}

type EscapeSeqJSONEncoder struct {
	zapcore.Encoder
}

func (enc *EscapeSeqJSONEncoder) Clone() zapcore.Encoder {
	return enc
}

func (enc *EscapeSeqJSONEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
	b, err := enc.Encoder.EncodeEntry(entry, fields)
	if err != nil {
		return nil, err
	}

	buf := buffer.NewPool().Get()
	replace := bytes.Replace(b.Bytes(), []byte("\\n"), []byte("\n"), -1)
	_, _ = buf.Write(bytes.Replace(replace, []byte("\\n"), []byte("\n"), -1))
	return buf, nil
}

func getLoggerWriter(filename string, maxSize int, maxBackups int, maxAge int) zapcore.WriteSyncer {
	// lumberjack 日志切割组件
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    maxSize,
		MaxBackups: maxBackups,
		MaxAge:     maxAge,
	}

	return zapcore.AddSync(lumberJackLogger)
}

func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format("2006-01-02 15:04:05"))
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = CustomTimeEncoder
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
	return &EscapeSeqJSONEncoder{
		Encoder: zapcore.NewJSONEncoder(encoderConfig),
	}
}

func InitZap() {
	writeSyncer := getLoggerWriter(Conf.Zap.Filename, Conf.Zap.MaxSize, Conf.Zap.MaxBackups, Conf.Zap.MaxAge)
	encoder := getEncoder()
	var level = new(zapcore.Level)
	err := level.UnmarshalText([]byte(Conf.Zap.Level))
	if err != nil {
		panic(err)
	}

	var core zapcore.Core
	if Conf.Mode == "dev" {
		core = zapcore.NewTee(
			zapcore.NewCore(encoder, writeSyncer, level),
			zapcore.NewCore(
				&EscapeSeqJSONEncoder{encoder},
				zapcore.Lock(os.Stdout),
				zapcore.DebugLevel,
			),
		)
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, level)
	}

	logger := zap.New(core, zap.AddCaller())
	zap.ReplaceGlobals(logger)
	zap.L().Info("init zap success")
	global.Logger = zap.L()
}

// GinLogger 重写gin中的logger
func GinLogger(c *gin.Context) {
	logger := zap.L()
	start := time.Now()
	path := c.Request.URL.Path
	query := c.Request.URL.RawQuery
	c.Next()
	cost := time.Since(start)
	logger.Info(
		path,
		zap.Int("status", c.Writer.Status()),
		zap.String("method", c.Request.Method),
		zap.String("path", path),
		zap.String("query", query),
		zap.String("ip", c.ClientIP()),
		zap.String("user-agent", c.Request.UserAgent()),
		zap.String("errors", c.Errors.ByType(gin.ErrorTypePrivate).String()),
		zap.String("cost", cost.String()),
	)
}

// GinRecovery 重写gin中的Recovery
func GinRecovery(stack bool) gin.HandlerFunc {
	logger := zap.L()
	return func(c *gin.Context) {
		// defer 延迟调用，出了异常，处理并恢复异常，记录日志
		defer func() {
			if err := recover(); err != nil {
				//1. 检查是否存在断开的连接(broken pipe或者connection reset by peer)
				var brokenPipe bool
				if ne, ok := err.(*net.OpError); ok {
					if se, ok := ne.Err.(*os.SyscallError); ok {
						if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
							brokenPipe = true
						}
					}
				}

				httpRequest, _ := httputil.DumpRequest(c.Request, false)
				if brokenPipe {
					logger.Error(
						c.Request.URL.Path,
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
					_ = c.Error(err.(error))
					c.Abort()
					return
				}

				//2. 是否打印堆栈信息，使用的是debug.Stack()，传入false，在日志中就没有堆栈信息
				if stack {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
						zap.String("stack", string(debug.Stack())),
					)

				} else {
					logger.Error("[Recovery from panic]",
						zap.Any("error", err),
						zap.String("request", string(httpRequest)),
					)
				}

				//3. 向前端或接口调用方返回错误
				c.AbortWithStatus(http.StatusInternalServerError)
				c.JSON(http.StatusInternalServerError, gin.H{"msg": "系统内部错误",
					"code": http.StatusInternalServerError,
				})
			}
		}()
		c.Next()
	}
}
